package com.sky.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        log.info("开始创建redis模板对象...");
        RedisTemplate redisTemplate = new RedisTemplate();
        //设置redis的连接工厂对象
        redisTemplate.setConnectionFactory(factory);
        //设置redis key 的序列化器
         //redisTemplate.setKeySerializer(new StringRedisSerializer());
         //redisTemplate.setValueSerializer(new StringRedisSerializer());

        // 设置正确的序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key使用String序列化
        redisTemplate.setKeySerializer(stringRedisSerializer);
        // hash的key也使用String序列化
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        // value使用JSON序列化
//        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(String.valueOf(Object.class));
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();

         return redisTemplate;

    }
}
